<?php

namespace App\Http\Controllers\Common;

use App\Helpers\Check;
use App\Helpers\ResponseEnum;
use App\Http\Controllers\Controller as BaseController;
use App\Http\Responses\CustomResponse;
use App\Models\AdminApplication;
use App\Services\common\FileService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Storage;
use OSS\OssClient;
use Validator;

/**
 * 附件
 * User: zhx
 * Date: 2023/10/25 0025
 * Time: 15:38
 */
class FileStoragesController extends BaseController
{
    /**
     * 附件列表
     * User: zhx
     * Date: 2023/10/25 0025
     * Time: 15:38
     */
    public function index(Request $request)
    {
        $list = FileService::getPageData($request->all());

        return CustomResponse::success($list);
    }

    /**
     * 上传文件
     * User: zhx
     * Date: 2023/10/25 0025
     * Time: 14:13
     */
    public function update(Request $request)
    {
        $request->validate([
            'file' => 'required|file',
        ]);

        $storage = config('amis.storage');
        $file = $request->file('file');
        $platformId = $request->input('platform_id', 0);

        if ($storage['location'] == 0) {
            return CustomResponse::error('请使用其他存储方式');
        } elseif ($storage['location'] == 1) {
            // 阿里云OSS上传
            // 目录名称 平台ID/images/20230101
            $file_path = $platformId.'/images/'.date('Ymd');
            // 原文件名称
            $original_name = $file->getClientOriginalName();
            // 新文件名称
            $filename = $file_path.'/'.md5(Hash::make($original_name)).'.'.$file->getClientOriginalExtension();
            // 获取文件列别
            $fileType = Check::getFileType($file->getClientOriginalExtension(), $file->getMimeType());

            try {
                $ossClient = new OssClient($storage['accessKeyId'], $storage['accessKeySecret'], $storage['ossEndpoint']);
                $res = $ossClient->uploadFile($storage['bucket'], $filename, $file->getPathName());
                $path = $res['info']['url'];

                if ($request->input('type') == 'tinymac') {
                    $this->add($fileType['type'], $file->getClientMimeType(), $file->getSize(), $filename, $path, $file->getClientOriginalName(), $request->global['user']['id'], $platformId);
                    $data = [
                        'code' => 0,
                        'msg' => '上传成功',
                        'data' => $path,
                    ];

                    return Response::json($data);
                } else {
                    if ($res) {
                        $this->add($fileType['type'], $file->getClientMimeType(), $file->getSize(), $filename, $path, $file->getClientOriginalName(), $request->global['user']['id'], $platformId);

                        return CustomResponse::success(['value' => $path]);
                    } else {
                        return CustomResponse::error('上传失败');
                    }
                }
            } catch (OssException $e) {
                return CustomResponse::error($e->getMessage());
            }
        }
    }

    /**
     * 保存文件信息
     * User: zhx
     * Date: 2023/10/25 0025
     * Time: 15:20
     */
    private function add($type, $mime, $size, $md5, $path, $name, $uid, $platform_id)
    {
        FileService::create([
            'type' => $type,
            'mime' => $mime,
            'size' => $size,
            'md5' => $md5,
            'path' => $path,
            'name' => $name,
            'uid' => $uid,
            'platform_id' => $platform_id,
        ]);
    }

    /**
     * 删除
     *
     * @return \Illuminate\Http\JsonResponse
     *
     * @author: hongbinwang
     *
     * @time  : 2021/8/12 23:03
     */
    public function delete(Request $request, $id)
    {
        $storage = config('amis.storage');
        $info = FileService::info($id);
        if ($info) {
            $ossClient = new OssClient($storage['accessKeyId'], $storage['accessKeySecret'], $storage['ossEndpoint']);
            try {
                // 删除文件
                $ossClient->deleteObject($storage['bucket'], $info->path);
                FileService::destroy([$id]);

                return CustomResponse::success([$id], '文件删除成功');
            } catch (\Exception $e) {
                return CustomResponse::error($e->getMessage());
            }
        } else {
            return CustomResponse::error('图片不存在或已被删除');
        }
    }

    /**************************************************************************************/

    /**
     * 平台OSS上传
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function upload_oss_file(Request $request)
    {
        //----------------------------------------------------
        // 验证
        //----------------------------------------------------
        $validator = Validator::make($request->all(), [
            'platform_id' => 'required',
            'file' => 'required|file',
        ]);
        if ($validator->fails()) {
            return $this->fail(ResponseEnum::CLIENT_PARAMETER_ERROR, null, $validator->errors()->first());
        }

        // 获取应用
        $application = AdminApplication::where('id', $platform->app_id)->first();

        // $data4->storage_disks->id == 1 本地 | $data4->storage_disks->id == 2 阿里云
        if ($data4['storage_disks']['id'] == 2) {
            // 文件信息
            $file_obj = $request->file;
            $file_path = $application->module.'/images/'.date('Ymd');
            $original_name = $file_obj->getClientOriginalName();
            $hash_name = md5(Hash::make($original_name));
            $filename = $hash_name.'.'.$file_obj->getClientOriginalExtension();

            $accessKeyId = $data4['AccessKeyId'];
            $accessKeySecret = $data4['AccessKeySecret'];
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            $endpoint = $data4['OSS_ENDPOINT'];
            // 填写Bucket名称，例如examplebucket。
            $bucket = $data4['bucket']; //
            //上传到阿里云存储后保存的文件名
            $file = $file_path.'/'.$filename;
            try {
                $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
                $res = $ossClient->uploadFile($bucket, $file, $request->file('file')->getPathName());
                $result_url = $res['info']['url'];

                if ($request->input('type') == 'tinymac') {
                    $data = [
                        'code' => 0,
                        'msg' => '上传成功',
                        'data' => $result_url,
                    ];

                    return Response::json($data);
                } else {
                    if ($res) {
                        return $this->success(['path' => $result_url]);
                    } else {
                        return $this->fail(ResponseEnum::HTTP_ERROR, [], '上传失败');
                    }
                }

            } catch (OssException $e) {
                return $this->fail(ResponseEnum::HTTP_ERROR, [], $e->getMessage());

                return json_encode(['code' => 422, 'msg' => $e->getMessage()]);
            }
        } else {
            // 本地上传
            // 文件信息
            $file_obj = $request->file;
            $file_path = 'module/'.$application->module.'/images/'.date('Ymd');
            $original_name = $file_obj->getClientOriginalName();
            $hash_name = md5(Hash::make($original_name));
            $filename = $hash_name.'.'.$file_obj->getClientOriginalExtension();

            $storage = Storage::disk('admin');
            $path = $storage->putFileAs($file_path, $file_obj, $filename);

            $resData = [
                'base_url' => '',
                'path' => $path,
                'uploads_path' => '/uploads/'.$path,
                'link' => $storage->url($path),
                'type' => $storage->mimeType($path),
                'size' => $storage->size($path),
                'name' => $filename,
                'original_name' => $original_name,
                'upload_ip' => $request->getClientIp(),
                'hash' => Hash::make($original_name),
            ];
            if ($request->input('type') == 'tinymac') {
                $data = [
                    'code' => 0,
                    'msg' => '上传成功',
                    'data' => $resData['link'],
                ];

                return Response::json($data);
            } else {
                return $this->success([
                    'path' => $resData['uploads_path'],
                    'link' => $resData['link'],
                ]);
            }
        }

    }
}
